package cn.edu.hbpu.service.impl;

import cn.edu.hbpu.dto.AdminUser;
import cn.edu.hbpu.entity.sys.SysUser;
import cn.edu.hbpu.handler.CustomException;
import cn.edu.hbpu.mapper.SysUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

import static cn.edu.hbpu.common.Constants.NONE_PROVIDED;

/**
 * @author lcy
 * @date 2022/8/4 8:17
 * @description
 */
@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        // 有时候前端没有传递用户名，此时用户名就是这个
        if (NONE_PROVIDED.equals(userName)) {
            throw new CustomException("用户名或密码错误");
        }

        // 1. 根据用户名查找用户信息
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUserName, userName);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        // 2. 判断是否存在该用户
        if (Objects.isNull(sysUser)) {
            throw new CustomException("用户名或密码错误");
        }

        // 3. 查询用户所对应的权限并存入loginUser中
        List<String> permissions = sysUserMapper.selectAllPermissions(sysUser.getSysUserId());
        log.info("{} 用户所具有的权限为 {}", sysUser.getNickName(), permissions);

        // 4. 保存权限信息到sysUser，方便前端获取该用户的权限
        sysUser.setPermissions(permissions);

        // 4. 将用户信息封装并返回
        return new AdminUser(sysUser, permissions);
    }
}
